<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/5
 * Time: 9:26
 */

namespace app\index\server;

use app\index\model\Product as ProductModel;
use app\index\model\ProductBanner;
use app\index\model\ProductImage as ProductImageModel;
use app\index\model\ProductInfo as ProductInfoModel;
use app\index\model\ProductProperty;
use app\index\model\Theme as ThemeModel;
use app\index\model\ThemeProduct as ThemeProductModel;
use app\lib\exception\DatabaseException;
use think\cache\driver\Redis;
use think\Exception;

class ProductServer extends BaseServer
{
    public function getProductList($id, $offset, $limit = 6)
    {
        // 根据 type 判断是 theme or category
//        $type_array = config('product');
//        if(!isset($type_array[$type])) {
//            // 抛出 传入类型出错
//        }
//        $type = $type_array[$type];
//        switch ($type) {
//            case 'theme' :
//                $list = $this->themeList($id, $offset, $limit);
//                break;
//            default :
//                $list = $this->categoryList($id, $offset, $limit);
//                break;
//        }
        $list = $this->themeList($id, $offset, $limit);
        return $list;
    }

    public function themeList($id, $page, $limit = 6)
    {
        try {
            if(!$page) {
                $offset = 0;
            } else {
                $offset = intval($page) * $limit - 1;
            }
            $theme_list = ThemeProductModel::with(['products' => function($query) {
                $query->with(['productInfo' => function($que) {
                    $que->where('stock', '>', 0)->order('id', 'desc')->limit(1);
                }]);
            }])
                ->where('theme_id', '=', $id)
                ->order('product_id', 'desc')
                ->limit($offset,6)
                ->select();
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => 20004,
                'msg' => $e->getMessage()
            ]);
        }
        return $theme_list;
    }

    public function categoryList($id, $offset, $limit = 6)
    {
        try {
            $product = ProductModel::where('category_id', $id)
                ->where('status', '=', 1)
                ->order('id', 'desc')
                ->limit($limit)
                ->select();
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => 20004,
                'msg' => '非常抱歉查询商品列表出错'
            ]);
        }
        return $product;
    }

    // 获取商品的主页信息 is_home
    public function getProductInfo($id)
    {
        // id 是 product表 的id
        try {
            $info = ProductInfoModel::with(['product'])
                ->alias('pi')
                ->where('status', '=', 1)
                ->where('is_home', '=', '1')
                ->where('stock', '>', 0)
                ->where('pi.product_id', $id)
                ->find();
            if(!$info) {
                // 查找一个
                $info = ProductInfoModel::where('status', '=', 1)
                    ->where('product_id', $id)
                    ->order('id', 'desc')
                    ->where('stock', '>', 0)
                    ->limit(1)
                    ->find();
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => 30061,
                'msg' => '非常抱歉查询商品详情出错'
            ]);
        }
        return $info;
    }

    public function getProductImg($id)
    {
        // id 是 product表 的id
        try {
            $img = ProductImageModel::with(['img'])
                ->where('status', '=', 1)
                ->where('product_id', $id)
                ->limit(10)
                ->select();
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => 30022,
                'msg' => '非常抱歉查询商品详情出错'
            ]);
        }
        return $img;
    }

    public function productInfo($id)
    {
        // id 是 product表 的id 只要几个字段而不是全部
        try {
            $info = ProductInfoModel::where('status', '=', 1)
                ->where('product_id', $id)
                ->order('id', 'desc')
                ->where('stock', '>', 0)
	       ->group('color')
                ->select();
            if(!$info) {
                $info = ProductInfoModel::where('status', '=', 1)
                    ->where('product_id', $id)
                    ->where('is_home', '<>', 1)
                    ->where('stock', '>', 0)
		  ->group('color')
                    ->order('id', 'desc')
                    ->select();
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => 30021,
                'msg' => '非常抱歉查询商品详情出错'
            ]);
        }
        return $info;
    }

    // 获取商品product 的Banner图
    public function getProductBanner($id)
    {
        try{
            $banner = ProductBanner::where('product_id', $id)
                ->where('status', '=', 1)
                ->order('id', 'asc')
                ->select();
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => '',
                'msg' => '非常抱歉获取商品轮播出错'
            ]);
        }
        return $banner;
    }

    // 获取商品的 property
    public function getProductProperty($id)
    {
        try {
            $property = ProductProperty::where('product_id', $id)
                ->where('status', 1)
                ->order('id', 'asc')
                ->select();
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => '',
                'msg' => '非常抱歉获取商品属性出错'
            ]);
        }
        return $property;
    }

    // 获取 size 信息
    public function size($params = [])
    {
        try {
            $result = ProductInfoModel::with(['user'])
            	->where('product_id', '=', $params['product_id'])
                ->where('color', '=', $params['color'])
                ->where('stock', '>', 0)
                ->field('size,id,product_id,color,price,member_price')
                ->select();
            if(!$result) {
                return setMsg(0, '未找到此商品此颜色/型号的商品');
            }
            $result['0']['isvip'] = session('Auth.IsVIP');
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => '',
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, 'OK', $result);
    }

    public function home($id)
    {
        try {
            $home = ProductInfoModel::where('status', '=', 1)
                ->where('product_id', $id)
                ->where('is_home', '=', '1')
                ->where('stock', '>', 0)
                ->find();
            if (!$home) {
                $home = ProductInfoModel::where('status', '=', 1)
                    ->where('product_id', $id)
                    ->where('is_home', '<>', '1')
                    ->where('stock', '>', 0)
                    ->order('id', 'desc')
                    ->limit(1)
                    ->find();
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => 30021,
                'msg' => '非常抱歉查询商品详情出错'
            ]);
        }
        return $home;
    }

    public function countNum()
    {
       $username = session('Auth.Username');
       if($username) {
           $redis = new Redis();
           $key = $username . ':counts';
           $counts = $redis->get($key);
           return $counts;
       }
    }

    public function getThemeId($name)
    {
        try {
            $result = ThemeModel::where('name', $name)
                ->field('id,name')
                ->find();
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => '',
                'msg' => $e->getMessage()
            ]);
        }
        return $result;
    }

    public function getProductId($name)
    {
        try {
            $result = ProductModel::where('name', $name)
                ->field('id,name')
                ->find();
        } catch (Exception $e) {
            throw new DatabaseException([
                'errorCode' => '',
                'msg' => $e->getMessage()
            ]);
        }
        return $result;
    }
}